package com.daiyang.lottery.service.impl;

import com.daiyang.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.daiyang.lottery.common.exception.ServiceException;
import com.daiyang.lottery.common.util.*;
import com.daiyang.lottery.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private RedisUtil redisUtil;


    private  static final String VERIFICATION_CODE_PREFIX = "verification_code_";
    private  static final Long VERIFICATION_CODE_EXPIRE_TIME = 60L;
    private  static final String VERIFICATION_CODE_TEMPLATE_CODE = "SMS_123456789";


    @Override
    public void sendVerificationCode(String phoneNumber) {
        //手机校验
        if(!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //发送验证码
        String code=CapchaUtil.generateCaptchaCode(4);
        Map<String,String> templateParam=new HashMap<>();
        templateParam.put("code",code);

        //发送验证码
        smsUtil.sendMessage(VERIFICATION_CODE_TEMPLATE_CODE, phoneNumber, JacksonUtil.writeValueAsString(templateParam));

        //存储验证码到redis
        redisUtil.set(VERIFICATION_CODE_PREFIX+phoneNumber,code,VERIFICATION_CODE_EXPIRE_TIME);

    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        if(!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX+phoneNumber);
    }
}
